// Tierless
// Copyright © 2010 Alphora
// This file is licensed under a modified BSD-license (see tierless_license.txt).
using System;
using System.Collections.ObjectModel;
using System.Text;

namespace Tierless.Framework.EntityTypes
{
	/// <summary>
	/// Represents a typed collection of <see cref="NamedEntityTypeObject"/> instances.
	/// </summary>
	/// <typeparam name="T"></typeparam>
	public class NamedEntityObjectTypeCollection<T> : ObservableCollection<T>
		where T : NamedEntityTypeObject
	{
		/// <summary>
		/// Determines the index of an object with a specific name in the collection.
		/// </summary>
		/// <param name="objectName">The name of the object.</param>
		/// <returns>The index of the object with the given name, if it exists, -1 otherwise.</returns>
		public int IndexOf(string objectName)
		{
			for (var index = 0; index < Count; index++)
				if (this[index].Name == objectName)
					return index;

			return -1;
		}

		/// <summary>
		/// Determines whether the collection contains a specific object.
		/// </summary>
		/// <param name="objectName"></param>
		/// <returns>True if the collection contains an object with the given name, false otherwise.</returns>
		public bool Contains(string objectName)
		{
			return IndexOf(objectName) >= 0;
		}

		/// <summary>
		/// Gets the object with the given name.
		/// </summary>
		/// <param name="objectName">The name of the object to be retrieved.</param>
		/// <returns>The object with the given name.</returns>
		public T this[string objectName]
		{
			get
			{
				var index = IndexOf(objectName);
				if (index < 0)
					throw new ArgumentException(String.Format("Object '{0}' not found.", objectName));

				return this[index];
			}
		}

		/// <summary>
		/// Returns a string representation of the collection.
		/// </summary>
		/// <returns>A string representation of the collection.</returns>
		public override string ToString()
		{
			var builder = new StringBuilder();
			foreach (var item in this)
				builder.AppendFormat("{0};", item);
			return builder.ToString();
		}
	}
}